package com.tanhua.dubbo.server.peachblossom.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.api.PeachBlossomApi;
import com.tanhua.dubbo.server.pojo.PeachBlossom;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

@Service(version = "1.0.0")
public class PeachBlossomApiImpl implements PeachBlossomApi {

    //最大次数
    private int number = 10;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public PeachBlossom queryPeach(Long userID,int sex) {
        try {
            Query query = new Query(Criteria.where("userId").is(userID));
            if (sex == 1  || sex == 3){
                PeachBlossom peachblossom_male = this.mongoTemplate.findOne(query, PeachBlossom.class, "peachblossom_male");
                return peachblossom_male;
            }
            else if (sex == 2){
                PeachBlossom peachblossom_female = this.mongoTemplate.findOne(query, PeachBlossom.class, "peachblossom_female");
                return peachblossom_female;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }


    @Override
    public Boolean savePeach(String url, Long userId,int sex) {
        try {
            PeachBlossom peachblossom = new PeachBlossom();
            peachblossom.setId(new ObjectId());
            peachblossom.setCreated(System.currentTimeMillis());
            peachblossom.setSoundUrl(url);
            peachblossom.setUserId(userId);
            if (sex == 1  || sex == 3){
                this.mongoTemplate.save(peachblossom,"peachblossom_male");
                return true;
            }else if (sex == 2){
                this.mongoTemplate.save(peachblossom,"peachblossom_female");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


    @Override
    public Boolean updatePeach(String url, Long userId,int sex) {
        try {
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId));
            Update update = Update.update("soundUrl", url);
            Update update1 = Update.update("created", System.currentTimeMillis());
            if (sex == 1  || sex == 3){
                this.mongoTemplate.upsert(query, update,"peachblossom_male");
                this.mongoTemplate.upsert(query, update1,"peachblossom_male");
                return true;
            }else if (sex == 2){
                this.mongoTemplate.upsert(query, update,"peachblossom_female");
                this.mongoTemplate.upsert(query, update1,"peachblossom_female");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean removePeachById(Long userId , int sex) {

        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);

        String tableName = "peachblossom_";
        if( sex == 1 || sex == 3 ){
            tableName += "male";
        }else{
            tableName += "female";
        }
        DeleteResult remove = this.mongoTemplate.remove(query, PeachBlossom.class, tableName);
        if( remove != null ){
            return true;
        }
        return false;
    }

    @Override
    public List<PeachBlossom> queryPeachList() {
        List<PeachBlossom> malePeachBlossomList = this.mongoTemplate.findAll(PeachBlossom.class,"peachblossom_male");
        List<PeachBlossom> femalePeachBlossomList = this.mongoTemplate.findAll(PeachBlossom.class,"peachblossom_female");

        List<PeachBlossom> allPeachBlossomList = new ArrayList<>();

        allPeachBlossomList.addAll(malePeachBlossomList);
        allPeachBlossomList.addAll(femalePeachBlossomList);


        if( allPeachBlossomList == null ){
            return null;
        }
        return allPeachBlossomList;
    }


    @Override
    public List<PeachBlossom> getPeachBlossomList(Long userId, Integer sex) {
        //获得 男表的 count  和 女表 的 count
        List<PeachBlossom> peachBlossomList = new ArrayList<>();

        Criteria criteria = Criteria.where("userId").ne(userId);
        Query query = Query.query(criteria);

        int maleCount = Long.valueOf(this.mongoTemplate.count(query, PeachBlossom.class, "peachblossom_male")).intValue();
        int femaleCount = Long.valueOf(this.mongoTemplate.count(query, PeachBlossom.class, "peachblossom_female")).intValue();
        // 0 说明没有数据，自动填充一条
        //初始化一条数据
        if( maleCount==0 ){
            maleCount++;
            savePeach("null", 11019L, 1);
        }
        if( femaleCount==0 ){
            femaleCount++;
            savePeach("null", 11018L, 2);
        }

        int count = maleCount + femaleCount;


        if (count <= 0) {
            return null;
        }

        //性别权重比例
        double qz = 0.7;
        int female = 0;
        int male = 0;
        //性别判断,如果是userId是男--> 男女比列 3:7
        if( sex ==1 || sex ==3 ){
            female = (int) (number*qz);
            male = number - female;
        }else{
            female = (int) (number*(1-qz));
            male = number - female;
        }


        List<Integer> femalelist = new ArrayList<>();
        List<Integer> malelist = new ArrayList<>();
        // count总人数 小于 最大次数

        getList(femaleCount, female, femalelist);
        getList(maleCount, male, malelist);

        //女信息
        System.out.println("femalelist = " + femalelist);
        fillPeachBlossomList(userId, peachBlossomList, femalelist,"peachblossom_female");

        //男信息
        System.out.println("malelist = " + malelist);
        fillPeachBlossomList(userId, peachBlossomList, malelist,"peachblossom_male");

        //再次打乱顺序
        Collections.shuffle(peachBlossomList);

        return peachBlossomList;
    }

    private void fillPeachBlossomList(Long userId, List<PeachBlossom> peachBlossomList, List<Integer> list,String tableName) {
        for (Integer index : list) {
            Query query1 = new Query().skip(index).limit(1);
            //排重
            while( this.mongoTemplate.find(query1, PeachBlossom.class,tableName).get(0).getUserId() == userId ){
                index++;
                while( list.contains(index) ){
                    index++;
                    query1 = new Query().skip(index).limit(1);
                }
            }
            System.out.println("index = " + index);
            peachBlossomList.add(this.mongoTemplate.find(query1, PeachBlossom.class,tableName).get(0));
        }
    }

    private static void getList(int count, int number, List<Integer> list) {
        if (count < number) {
            for (int i = 0; i < count; i++) {
                int rs = new Random().nextInt(count);
                if (list.contains(rs)) {
                    i--;
                } else {
                    list.add(rs);
                }
            }
            for (int i = 0; i < (number - count); i++) {
                int rs = new Random().nextInt(count);
                list.add(rs);
            }
        } else {
            for (int i = 0; i < number; i++) {
                int rs = new Random().nextInt(count);
                if (list.contains(rs)) {
                    i--;
                } else {
                    list.add(rs);
                }
            }
        }
    }


}
